[模板]二分图最大匹配

2019-11-06
模板

题意

求二分图最大匹配

题解

能协商就协商

调试记录

每次bfs前要清空vis

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <cstdio>
#include <cstring>
const int maxn = 1e6 + 5;
using namespace std;
struct E{
int to, nxt;
}e[maxn << 1];
int head[maxn], tot = 0;
void addedge(int u, int v){
e[++tot].to = v, e[tot].nxt = head[u];
head[u] = tot;
}
bool vis[maxn]; int match[maxn][2];
bool bfs(int cur){
for (int i = head[cur]; i; i = e[i].nxt){
int v = e[i].to;
if (!vis[v]){
vis[v] = 1;
if (!match[v][1] || bfs(match[v][1])){
match[v][1] = cur;
match[cur][0] = v;
return true;
}
}
}
return false;
}
int n, m, q;
int main(){
scanf("%d%d%d", &n, &m, &q);
for (int u, v, i = 1; i <= q; i++){
scanf("%d%d", &u, &v);
if (u > n || v > m) continue;
addedge(u, v);
}
int ans = 0;
for (int i = 1; i <= n; i++)
if (!match[i][0]){
memset(vis, 0, sizeof vis);
ans += bfs(i);
}
printf("%d\n", ans);
return 0;
}